<template>
  <view class="subscribe" :style="{ backgroundImage: `url(${baseUrl}/images/bg-5.png)` }">
    <view class="record" @click="goToRecord">
      <text>预约记录</text>
      <image src="/reservation-images/icon-right.svg" mode="widthFix" style="width: 30rpx; height: 30rpx" />
    </view>
    <view class="card">
      <view class="card-title">参观园区</view>
      <swiper circular class="card-swiper" :current="swiperIndex" @change="handleSwiperChange">
        <swiper-item class="swiper-item" v-for="(item, index) in cardList" :key="index">
          <view class="card-image">
            <image :src="item.image" mode="widthFix" />
          </view>
        </swiper-item>
      </swiper>
      <view class="name">
        {{ currentGround.title }}
        <view class="swiper-left" @click="handleSwiperLeft">
          <image src="/reservation-images/icon-right-y.svg" mode="widthFix" />
        </view>
        <view class="swiper-right" @click="handleSwiperRight">
          <image src="/reservation-images/icon-right-y.svg" mode="widthFix" />
        </view>
      </view>
      <view class="desc">
        {{ currentGround.detail }}
      </view>
      <!-- 分割线 -->
      <view class="line"></view>
      <!-- 到访时间 -->
      <view class="time">
        <view class="form-item" style="margin-bottom: 0rpx">
          <view class="form-item__label">到访时间</view>
          <view class="form-item__value" @click="handleDate">
            <view class="form-item__value-text">
              <text v-if="formData.reservation_date && formData.reservation_time">
                {{ formData.reservation_date }} {{ formData.reservation_time }}
              </text>
              <text v-else class="form-item__value-text-placeholder">
                请选择到访日期及时间
              </text>
            </view>
            <image src="/reservation-images/icon-right-y.svg" mode="widthFix" />
          </view>
        </view>
      </view>
    </view>
    <view class="card" style="padding-top: 60rpx">
      <view class="form-item">
        <view class="form-item__label">预约人姓名</view>
        <view class="form-item__value">
          <input type="text" v-model="formData.realname" placeholder="请填写访客姓名"
            placeholder-style="color: #fff;opacity: 0.5" />
        </view>
      </view>
      <!-- <view class="form-item">
        <view class="form-item__label">预约人手机</view>
        <view class="form-item__value">
          <view class="area">
            <view>+86</view>
            <image src="/reservation-images/icon-right-y.svg" mode="widthFix" />
          </view>
          <view class="area-line"></view>
          <input
            type="text"
            maxlength="11"
            v-model="formData.telephone"
            placeholder="请输入手机号"
            placeholder-style="color: #fff;opacity: 0.5"
          />
        </view>
      </view> -->
      <!-- 验证码 -->
      <view class="phone-code">
        <view class="form-item" style="flex: 1">
          <view class="form-item__label">预约人手机</view>
          <view class="form-item__value">
            <input type="number" maxlength="11" v-model="formData.telephone" placeholder="请填写手机号"
              placeholder-style="color: #fff;opacity: 0.5" />
          </view>
        </view>
        <button class="phone-code-btn" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">获取手机号</button>
      </view>
      <!-- 访客人数 -->
      <view class="form-item">
        <view class="form-item__label">访客人数</view>
        <view class="form-item__value">
          <input type="number" v-model="formData.visitor_number" placeholder="请填写访客人数"
            placeholder-style="color: #fff;opacity: 0.5" />
        </view>
      </view>
      <!-- 访客类型 -->
      <view class="form-item" style="margin-bottom: 0rpx">
        <view class="form-item__label">访客类型</view>
        <view class="form-item__value" @click="handleType">
          <input type="text" v-model="formData.typeStr" readonly placeholder="请选择访客类型"
            placeholder-style="color: #fff;opacity: 0.5" />
          <image src="/reservation-images/icon-right-y.svg" mode="widthFix" />
        </view>
      </view>
    </view>
    <!-- 提交按钮 -->
    <view class="submit-btn" @click="handleSubmit">
      <fh-button>确认预约</fh-button>
    </view>

    <!-- 到访日期弹窗 -->
    <uni-popup ref="datePanelRef" :safe-area="false">
      <view class="popup-box" style="max-height: 85vh">
        <view class="popup-header">
          <view class="title">到访时间</view>
          <view class="close" @click="datePanelRef.close()">
            <image src="/reservation-images/close.png" mode="widthFix" />
          </view>
        </view>
        <view class="popup-content">
          <view class="date-card">
            <view class="date-item" v-for="(item, index) in dateList" :key="index" @click="handleDateItemClick(item)"
              :class="{
                'date-item-active': item.is_selected,
                'date-item-disabled': item.is_open == 0,
              }">
              <view class="date-item-week">{{ item.week }}</view>
              <view class="date-item-day">{{ item.dayStr }}</view>
            </view>
          </view>
          <view class="date-line"></view>
          <view class="time-card">
            <view class="time-item" v-for="(item, index) in timeList" :key="index" @click="handleTimeItemClick(item)"
              :class="{
                'time-item-active': item.is_selected,
                'time-item-disabled': item.is_open == 0,
              }">
              <view class="time-item-day" style="text-align: center;">
                <view>{{ item.time }}</view>
                <view v-if="item.is_open == 0">{{ item.status }}</view>
              </view>
            </view>
          </view>
        </view>
        <view class="popup-footer" @click="handleDateConfirm">
          <fh-button>确认选择</fh-button>
        </view>
      </view>
    </uni-popup>
    <!-- 访客类型下拉框 -->
    <uni-popup ref="typePanelRef" :safe-area="false">
      <view class="popup-box" style="max-height: 85vh">
        <view class="popup-header">
          <view class="title">访客类型</view>
          <view class="close" @click="typePanelRef.close()">
            <image src="/reservation-images/close.png" mode="widthFix" />
          </view>
        </view>
        <view class="popup-content">
          <picker-view :indicator-style="indicatorStyle" :indicator-class="indicatorClass" :value="typeValue"
            :mask-style="maskStyle" :immediate-change="true" @change="bindTypeChange" class="picker-view">
            <picker-view-column>
              <view class="item" v-for="(item, index) in typeList" :class="{ active: activeIndex == index }"
                :key="index">{{ item.name }}</view>
            </picker-view-column>
          </picker-view>
        </view>
        <view class="popup-footer" @click="handleTypeConfirm">
          <fh-button>确认选择</fh-button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { baseUrl } from '@/reservation/config'
import { ref, onMounted } from 'vue'
import {
  getDateConfig,
  getTimeConfig,
  reservation,
  getGround,
  decodePhone,
} from '@/api/reservation'
import fhButton from '../components/fh-button.vue'
defineOptions({
  name: 'subscribe',
})
const swiperIndex = ref(0)
// 工厂数据
const cardList = ref([])
// 当前选中的工厂信息
const currentGround = ref({
  ground: '',
  title: '',
  detail: '',
  image: '',
})
// 到访日期Ref
const datePanelRef = ref(null)
// 到访日期数据
const dateList = ref([])
// 到访时间数据
const timeList = ref([])
// 访客类型下拉框 配置
const typePanelRef = ref(null)
const indicatorStyle = ref('height: 50px')
const indicatorClass = ref('indicatorClass')
const maskStyle = ref('background: transparent !important;')
const typeValue = ref([0])
const activeIndex = ref(0)
// 访客类型数据
const typeList = ref([
  {
    type: 1,
    name: '内部学习/培训'
  },
  {
    type: 2,
    name: '产品/品牌体验'
  },
  {
    type: 3,
    name: '公众参观|科普教育'
  },
  {
    type: 4,
    name: '商业邀约/参观'
  },
  {
    type: 5,
    name: '社会团体/学术交流'
  },
  {
    type: 6,
    name: '政府考察/调研'
  },
  {
    type: 7,
    name: 'VIP/定向邀约'

  },
  {
    type: 8,
    name: '媒体/机构'
  },
  {
    type: 9,
    name: '其他'
  }
])



const formData = ref({
  openid: '', // 用户openid
  reservation_date: '', // 到访日期
  reservation_time: '', // 到访时间
  realname: '', // 姓名
  telephone: '', // 电话
  visitor_number: '', // 参观人数
  ground: '', // 工厂
  type: '', // 参观类型
  typeStr: '', // 参观类型名称
})

onMounted(async () => {
  // 获取工厂数据
  await getGround({
    openid: uni.getStorageSync('reservation_openid'),
  }).then((res) => {
    console.log(res, 'res')
    cardList.value = res.data
    // 设置当前选中的工厂
    currentGround.value = cardList.value[0] || {}
  })
  // 获取到访日期
  getDateConfig({
    openid: uni.getStorageSync('reservation_openid'),
  }).then((res) => {
    dateList.value = res.data.map((item, index) => ({
      ...item,
      dayStr: formatDate(item.day),
    }))
    // 如果dateList 有值，则默认查询第一条数据的timeList
    if (dateList.value.length > 0) {
      getTimeList(dateList.value[0].day)
    }
  })
})
/**
 * 获取到访时间
 * @param day 到访日期 2025-07-11
 */
const getTimeList = (day) => {
  getTimeConfig({
    openid: uni.getStorageSync('reservation_openid'),
    day: day,
    ground: cardList.value[swiperIndex.value].ground || '',
  }).then((res) => {
    timeList.value = res.data
    console.log(timeList.value, 'timeList')
  })
}
/**
 * 获取手机号
 */
const decryptPhoneNumber = (e) => {
  console.log(e)
  let { errMsg, code = null } = e.detail
  if (errMsg == 'getPhoneNumber:ok') {
    decodePhone({
      openid: uni.getStorageSync('reservation_openid'),
      code,
    }).then((res) => {
      console.log(res, '---')
      formData.value.telephone = res.data.phone
    })
  }
}
/**
 * 访客类型下拉框 选择事件
 */
const handleType = () => {
  typePanelRef.value.open('bottom')
}
/**
 * 访客类型下拉框 确认选择事件
 */
const handleTypeConfirm = () => {
  formData.value.typeStr = typeList.value[activeIndex.value].name
  formData.value.type = typeList.value[activeIndex.value].type
  typePanelRef.value.close()
}

/**
 * 轮播图 左滑事件
 */
const handleSwiperLeft = () => {
  swiperIndex.value--
  if (swiperIndex.value < 0) {
    swiperIndex.value = cardList.value.length - 1
  }
}
/**
 * 轮播图 右滑事件
 */
const handleSwiperRight = () => {
  swiperIndex.value++
  if (swiperIndex.value >= cardList.value.length) {
    swiperIndex.value = 0
  }
}
/**
 * 访客类型下拉框 选择事件
 * @param e 事件对象
 */
const bindTypeChange = (e) => {
  console.log(e, 'e')
  activeIndex.value = e.detail.value[0]
  formData.value.type = typeList.value[activeIndex.value].type
}

/**
 * 轮播图切换事件
 * @param e 事件对象
 */
const handleSwiperChange = (e) => {
  swiperIndex.value = e.detail.current
  formData.value.ground = cardList.value[swiperIndex.value].ground || ''
  currentGround.value = cardList.value[swiperIndex.value] || {}
  console.log(currentGround.value, 'currentGround')
  getTimeList(dateList.value[0].day)
}

const handleDate = () => {
  datePanelRef.value.open('bottom')
}

// 自定义时间处理函数，后续可以替换 将 2025-07-11 转成 07-11
const formatDate = (date) => {
  // 保留月和日
  return date.split('-').slice(1).join('-')
}
/**
 * 到访日期点击事件
 * @param item 到访日期对象
 */
const handleDateItemClick = (item) => {
  if (item.is_selected || item.is_open == 0) return
  dateList.value.forEach((item) => {
    item.is_selected = false
  })
  item.is_selected = true
  // 设置formData.reservation_date
  formData.value.reservation_date = item.day
  getTimeList(item.day)
}
/**
 * 到访时间点击事件
 * @param item 到访时间对象
 */
const handleTimeItemClick = (item) => {
  if (item.is_selected || item.is_open == 0) return
  timeList.value.forEach((item) => {
    item.is_selected = false
  })
  item.is_selected = true
  // 设置formData.reservation_time
  formData.value.reservation_time = item.time
}
/**
 * 日期和时间确认选择
 */
const handleDateConfirm = () => {
  // 判断日期是否选择
  if (!formData.value.reservation_date) {
    uni.showToast({
      title: '请选择日期',
      icon: 'none',
    })
    return
  }
  // 判断时间是否选择
  if (!formData.value.reservation_time) {
    uni.showToast({
      title: '请选择时间',
      icon: 'none',
    })
    return
  }
  datePanelRef.value.close()
}
// 校验表单,返回promise
const validateForm = () => {
  return new Promise((resolve, reject) => {
    if (!formData.value.reservation_date) {
      reject('请选择日期')
    }
    if (!formData.value.reservation_time) {
      reject('请选择时间')
    }
    if (!formData.value.realname) {
      reject('请填写姓名')
    }
    if (!formData.value.telephone) {
      reject('请填写手机号')
    }
    if (!formData.value.visitor_number) {
      reject('请填写访客人数')
    }
    if (!formData.value.type) {
      reject('请选择访客类型')
    }
    resolve()
  })
}
const handleSubmit = () => {
  // 校验表单
  validateForm()
    .then(() => {
      reservation({
        ...formData.value,
        ground: currentGround.value?.ground || '',
        openid: uni.getStorageSync('reservation_openid'),
      }).then((res) => {
        console.log(res, 'res')
        if (res.code == 0) {
          uni.showToast({
            title: '预约成功',
            icon: 'success',
          })
          uni.redirectTo({
            url: '/reservation/status/index?id=' + res.data.id,
          })
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none',
          })
        }
      })
    })
    .catch((err) => {
      console.log(err, 'err')
      uni.showToast({
        title: err,
        icon: 'none',
      })
    })
}

const goToRecord = () => {
  uni.navigateTo({
    url: '/reservation/record/index',
  })
}
</script>

<style lang="less" scoped>
@import './index.less';
</style>
